#!/bin/bash

# 初始化环境变量
app_service="${app_service:-web-service}"
app_service_port="${app_service_port:-80}"
app_service_dist_zip="${app_service_dist_zip:-/tmp/dist.zip}"
app_service_dist_url="${app_service_dist_url:-}"
app_container_name="${app_container_name:-web-service}"
app_network="${app_network:-server_network}"

config_path=~/web/${app_service}/config
dist_path=~/web/${app_service}/dist

check_container() {
  if docker ps --format '{{.Names}}' | grep -q "^${app_container_name}$"; then
    echo "容器存在!"
    return 0
  else
    echo "容器不存在!"
    return 1
  fi
}

run_service() {
  echo "创建网络"
  echo "docker network create --attachable --driver bridge ${app_network}"
  docker network create --attachable --driver bridge ${app_network} || true

  echo "清理旧容器"
  echo "docker rm -f ${app_container_name}"
  docker rm -f ${app_container_name} || true

  echo "创建配置目录"
  echo "mkdir -p ${config_path}"
  mkdir -p ${config_path}
  echo "mkdir -p ${dist_path}"
  mkdir -p ${dist_path}

  copy_config_files

  download_dist_files

  echo "启动容器"
  echo "docker run --name ${app_container_name} \
            --network ${app_network} \
            -v ${config_path}:/etc/nginx/conf.d \
            -v ${dist_path}:/usr/share/nginx/html \
            -p ${app_service_port}:80 \
            -d nginx"
  docker run --name ${app_container_name} \
    --network ${app_network} \
    -v ${config_path}:/etc/nginx/conf.d \
    -v ${dist_path}:/usr/share/nginx/html \
    -p ${app_service_port}:80 \
    -d nginx
}

reload_service() {

  copy_config_files

  download_dist_files

  echo "重启容器"
  echo "docker restart ${app_container_name}"
  docker restart ${app_container_name}
}

clean_service() {
  echo "清除容器"
  echo "docker stop ${app_container_name}"
  docker stop ${app_container_name}
  echo "docker rm ${app_container_name}"
  docker rm ${app_container_name}

  echo "删除配置目录"
  echo "rm -rf ${config_path}"
  rm -rf ${config_path}
  echo "rm -rf ${dist_path}"
  rm -rf ${dist_path}
}

copy_config_files() {
  echo "复制配置文件"
  echo "cp -R ./release/config/* ${config_path}"
  cp -R ./release/config/* ${config_path}
}

download_dist_files() {
  echo "下载解压资源文件"
  echo "wget -q -O ${app_service_dist_zip} ${app_service_dist_url}"
  wget -q -O ${app_service_dist_zip} ${app_service_dist_url}
  echo "rm -rf ${dist_path}/*"
  rm -rf ${dist_path}/*
  echo "unzip -q ${app_service_dist_zip} -d ${dist_path}"
  unzip -q ${app_service_dist_zip} -d ${dist_path}
}


# 主逻辑
case $1 in
  check)
    check_container
    ;;
  run)
    if check_container; then
      reload_service
    else
      run_service
    fi
    ;;
  rerun)
    clean_service
    run_service
    ;;
  clean)
    clean_service
    ;;
  *)
    echo "Usage: $0 {check|run|rerun|clean}"
    exit 1
    ;;
esac